import 'dart:convert';

import 'package:regular_assess/helper/utils/httputils/urlpath.dart';
import 'package:regular_assess/pages/home/model/award_model.dart';

import '../../utils/util.dart';
import '../model/user/user_info.dart';
import 'state.dart';

class UserController {
  final state = UserState();

  static final UserController instance = UserController._interval();
  factory UserController() => instance;
  UserController._interval();

  AwardModel md = AwardModel(
    icon: 'appIcon.png'.imgPathCommon,
    html: '${UrlPath.baseUrl}/leadership-hf-app/#/login',
    // html: 'http://192.168.19.239:8083/',
    url: UrlPath.baseUrl,
  );
  String get urlOrigin {
    return Uri.parse(md.url!).origin;
  }

  String get userKey {
    return "${md.url ?? ''}-user";
  }

  String get tokenKey {
    return "${md.url ?? ''}-token";
  }

  Future<void> initData() async {
    String _token = SpUtil().getStr(tokenKey);
    if (_token.isEmpty) {
      return;
    }
    var _userStr = await SpUtil().getJSON(userKey);
    if (_userStr != null) {
      var _userJson = jsonDecode(_userStr);
      configUser(_userJson);
      if (isLogin) {}
    }
  }

  Future<void> loginSuccess(Map<String, dynamic> userJson) async {
    configUser(userJson);
    await save();
  }

  Future<void> loginOutSuccess() async {
    isLogin = false;
    state.user?.token = null;
    await SpUtil().remove(tokenKey);
  }

  void updateAvater(String avater) {
    if (state.user == null) {
      return;
    }
    // state.user?.updateAvater(avater);
    loginSuccess(state.user!.toJson());
  }

  void configUser(Map<String, dynamic> userJson) {
    isLogin = true;
    state.user = UserInfo.fromJson(userJson);
    state.userObs.value = state.user!;
    state.userObs.refresh();
  }

  final isLoginObs = false.obs;
  set isLogin(bool value) {
    isLoginObs.value = value;
    if (value == false) {
      SpUtil().remove(tokenKey);
    }
  }

  bool get isLogin {
    return !isNilStr(state.user?.token);
  }

  final isAtLoginObs = true.obs;
  set isAtLogin(bool value) => isAtLoginObs.value = value;
  bool get isAtLogin => isAtLoginObs.value;

  Future<bool> save() async {
    if (isNilStr(md.url)) {
      return false;
    }
    if (state.user != null) {
      var _json = state.user!.toJson();
      await SpUtil().setJSON(userKey, jsonEncode(_json));

      await SpUtil().setStr(tokenKey, state.user!.token!);
      return true;
    }
    return false;
  }

  void toWeb() {
    Get.offAllNamed(RouterPath.web_view, parameters: {
      'url': md.htmlUrl!,
      'safeArea': '1',
    });
  }
}
